package com.alinesno.cloud.common.web.login.aop;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alinesno.cloud.base.boot.entity.ManagerAccountEntity;
import com.alinesno.cloud.base.boot.entity.ManagerAccountRecordEntity;
import com.alinesno.cloud.base.boot.service.IManagerAccountRecordService;
import com.alinesno.cloud.common.core.utils.IPUtils;
import com.alinesno.cloud.common.web.login.aop.AccountRecord.RecordType;
import com.alinesno.cloud.common.web.login.session.CurrentAccountSession;

/**
 * 用户登陆及页面操作监控 , AOP切面 ：多个切面时，@Order(i)注解来标识切面的优先级。i的值越小，优先级越高,看方法运行的时间 
 * @author WeiXiaoJin
 * @since 2019年4月8日 下午8:30:43
 */
@Order(5)
@Aspect
@Component
public class AccountRecordAspect {
	
    @SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(AccountRecordAspect.class);
   
//    @Autowired
    @Autowired
    private IManagerAccountRecordService managerAccountRecordService ; 
   
    /**
     * 是否保存用户操作记录
     */
    @Value("${alinesno.cloud.logger.operation.save:true}")  
    private boolean saveOperationLogger ; 
    
    @Pointcut("@annotation(com.alinesno.cloud.common.web.login.aop.AccountRecord)")  
    public void pointcut(){
    }
 
    //统计请求的处理时间
    ThreadLocal<Long> startTime = new ThreadLocal<>();
   
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;
        long beginTime = System.currentTimeMillis();
        try {
            // 执行方法
            result = point.proceed();
        } catch (Throwable e) {
        	e.printStackTrace();
        }
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        
        // 保存日志
        monitorAccountOperator(point, time);
        
        return result;
    }

    /**
     * 记录用户操作日志
     * @param joinPoint
     * @param time
     */
    @Async
	public void monitorAccountOperator(ProceedingJoinPoint joinPoint, long time) {
		ManagerAccountRecordEntity bean = new ManagerAccountRecordEntity() ; 
		
		bean.setMethodTime(time);
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String className = joinPoint.getTarget().getClass().getName(); // 请求的方法名
        String methodName = signature.getName();
        bean.setMethod(className+":"+methodName);
        
        AccountRecord accountRecord = method.getAnnotation(AccountRecord.class) ; 
        String value = accountRecord.value() ; 
        String type = accountRecord.type().value() ; 
        
        if(StringUtils.isBlank(value) && StringUtils.isNotBlank(type)) {
        	RecordType record = AccountRecord.RecordType.queryLabel(type) ; 
        	value = record.label() ; 
        }
        
        bean.setMethodDesc(value);
        bean.setRecordType(type);
        
        // 请求的方法参数值 请求的方法参数名称
        Object[] args = joinPoint.getArgs();
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        
        String[] paramNames = u.getParameterNames(method);
        if (args != null && paramNames != null) {
            String params = "";
            for (int i = 0; i < args.length; i++) {
                params += "  " + paramNames[i] + ": " + args[i];
            }
            bean.setParams(params);
        }
        
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes() ; 
        HttpServletRequest request = attributes.getRequest(); 
        String agent = request.getHeader("User-Agent");
        String url = request.getRequestURL().toString() ; 
        
        bean.setIp(IPUtils.getIpAddr(request)) ; 
        bean.setUrl(url);
        bean.setAgent(agent);
        
        // 设置用户
        ManagerAccountEntity account = CurrentAccountSession.get(request) ; 
        if(account != null) {
        	
        	bean.setAccountId(account.getId());
        	bean.setAccountName(account.getName());
        	bean.setApplicationId(account.getApplicationId()) ; 
        	bean.setLoginName(account.getLoginName()) ; 
        	
        	bean.setOperatorId(account.getId());
        }
        
        bean.setCreateTime(new Date());
       
        if(saveOperationLogger) {
        	managerAccountRecordService.save(bean) ; 
        }
    }
 
}


